package cn.donting.jme.core.state;

import cn.donting.jme.EditorContent;
import cn.donting.jme.editor.scene.SceneCamera;
import cn.donting.jme.expansion.tool.SceneTool;
import cn.donting.jme.ioc.Bean;
import com.jme3.app.state.AbstractAppState;
import com.jme3.scene.Node;
import com.jme3.scene.Spatial;
import lombok.extern.slf4j.Slf4j;

@Bean
@Slf4j
public class SceneToolState extends AbstractAppState {

    private SceneTool sceneTool;

    public void setSceneTool(SceneTool sceneTool) {
        Spatial select = null;
        SceneCamera sceneCamera = null;
        if (this.sceneTool != null) {
            Node toolNode = this.sceneTool.getToolNode();
            if (toolNode != null) {
                EditorContent.runJme(() -> EditorContent.getJmeApplication().getEditorNode().detachChild(toolNode));
            }
            select = this.sceneTool.getSelectSpatial();
            sceneCamera = this.sceneTool.getSelectCamera();
            this.sceneTool.setSelectSpatial(null);
            this.sceneTool.setSelectCamera(null);
            this.sceneTool.active(false);
        }
        if (sceneTool != null) {
            if(sceneCamera!=null){
                sceneTool.setSelectCamera(sceneCamera);
            }else {
                sceneTool.setSelectSpatial(select);
            }
            sceneTool.active(true);
            Node toolNode = sceneTool.getToolNode();
            EditorContent.runJme(() -> EditorContent.getJmeApplication().getEditorNode().attachChild(toolNode));
        }
        this.sceneTool = sceneTool;

    }

    public void setSelectSpatial(Spatial spatial){
        if (this.sceneTool!=null) {
            sceneTool.setSelectSpatial(spatial);
        }
    }
    public void setSelectCamera(SceneCamera sceneCamera){
        if (this.sceneTool!=null) {
            sceneTool.setSelectCamera(sceneCamera);
        }
    }
    @Override
    public void update(float tpf) {
        try {
            if (sceneTool != null) {
                sceneTool.update(tpf);
            }
        }catch (Exception ex){
            log.error(ex.getMessage(),ex);
        }
    }
}
